package org.aristotle.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.aristotle.auth.client.UserClient;
import org.aristotle.auth.constant.SysAuthConstant;
import org.aristotle.auth.constant.SysUser;
import org.aristotle.common.response.result.Result;
import org.aristotle.common.response.result.ResultCode;
import org.aristotle.user.model.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class JwtTokenUserDetailsService implements UserDetailsService {

    @Autowired
    private UserClient userClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Result<?> result = userClient.getUserByUsername(username);
        SysUser sysUser = null;
        if (ResultCode.QUERY_SUCCESS.getCode() == result.getCode().intValue()) {
            UserDTO user = JSONObject.parseObject(JSON.toJSONString(result.getData()),UserDTO.class);
            if (user != null) {

                // 获取权限(角色)
                List<String> roleList = user.getRoleList().stream()
                        .map(role -> SysAuthConstant.ROLE_PREFIX + role.getIdentifier())
                        .collect(Collectors.toList());

                sysUser = SysUser.builder()
                        .userId(user.getId().toString())
                        .username(user.getUsername())
                        .password(user.getPassword())
                        .authorities(AuthorityUtils.createAuthorityList(roleList.toArray(new String[roleList.size()])))
                        .enabled(user.getStatus() == 1)
                        .build();
            }
        }
        return sysUser;
    }
}
